{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# tf.GradientTape is an API for automatic differentiation - computing the gradient of\n",
    "# a computation with respect to its input variables. Tensorflow \"records\" all operations\n",
    "# executed inside the context of a tf.GradientTape onto a \"tape\"\n",
    "\n",
    "## Automatic differentiation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dz/dx= 108.0\n",
      "dy/dx= 6.0\n"
     ]
    }
   ],
   "source": [
    "x = tf.constant(3.0)\n",
    "with tf.GradientTape(persistent=True) as t:\n",
    "    t.watch(x)               # Ensures that `tensor` is being traced by this tape.\n",
    "    y = x * x\n",
    "    z = y * y\n",
    "dz_dx = t.gradient(z, x)  # 108.0 (4*x^3 at x = 3)\n",
    "dy_dx = t.gradient(y, x)  # 6.0\n",
    "print(\"dz/dx=\", dz_dx.numpy())\n",
    "print(\"dy/dx=\", dy_dx.numpy())\n",
    "del t  # Drop the reference to the tape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Recording control flow\n",
    "\n",
    "# Because tapes record operations as they are executed,\n",
    "# Python control flow (using ifs and whiles for example) is naturally handled"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(x, y):\n",
    "    output = 1.0\n",
    "    for i in range(y):\n",
    "        if i > 1 and i < 5:\n",
    "            output = tf.multiply(output, x)\n",
    "    return output\n",
    "\n",
    "def grad(x, y):\n",
    "    with tf.GradientTape() as t:\n",
    "        t.watch(x)\n",
    "        out = f(x, y)\n",
    "    return t.gradient(out, x)\n",
    "\n",
    "x = tf.convert_to_tensor(2.0)\n",
    "\n",
    "assert grad(x, 6).numpy() == 12.0\n",
    "assert grad(x, 5).numpy() == 12.0\n",
    "assert grad(x, 4).numpy() == 4.0"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
